<?php


class WSB_Controller_Plugin_Permission extends Zend_Controller_Plugin_Abstract
{

    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
		$auth = WSB_Auth_Backend::getInstance();
		if($auth->hasIdentity()) {
			$beuser = $auth->getIdentity();
			// In Layoutplatzhalter schreiben
			$this->getResponse()->append('auth_status', $beuser->username);
			$acl = $beuser->getAcl();
			if($acl instanceof Zend_Acl ) {

				$module		= strtolower($this->_request->getModuleName());
				$controller = strtolower($this->_request->getControllerName());
				$action 	= strtolower($this->_request->getActionName());

				// ---->
				// @todo: Die nachfolgenden Codezeilen entsprechen exakt dem Code in
				// WSB_Controller_Plugin_Navigation::_isAclAllowed();
		        $hasAccess = false;
		    	if($acl->isAllowed(WSB_ACL_ROLE_ADMIN)) {
		    		$hasAccess = true;
		    	} else {
		        	/* Wildcard access
						Alle moeglichen Kombinationen sind:
						*
						*.*
						page.*
						*.*.*
						*.*.index
						*.index.*
						*.index.index
						page.*.*
						page.*.index
						page.index.*
						page.index.index
		        	*/
		        	$_aros = array(
		        		// 1-stellig
		        		"*",
		        		// 2-stellig
		        		"$module.*",
		        		"*.*",
		        		// 3-stellig
		        		"*.*.*",
		        		"*.*.".$action,
		        		"*.$controller.*",
		        		"*.$controller.$action",
		        		"$module.*.*",
		        		"$module.*.$action",
		        		"$module.$controller.*",
		        		"$module.$controller.$action"
		        	);

		        	// Access
		        	foreach($_aros AS $_aro) {
		        		if($acl->isAllowed(WSB_ACL_ROLE_STAFF, 'DEFAULT', $_aro)) {
		        			$hasAccess = true;
		        			break;
		        		}
		        	}

		        	// Deny
		        	foreach($_aros AS $_aro) {
		        		if($acl->getRuleType($_aro, WSB_ACL_ROLE_STAFF, 'DEFAULT') == Zend_Acl::TYPE_DENY) {
		        			if(!$acl->isAllowed(WSB_ACL_ROLE_STAFF, 'DEFAULT', $_aro)) {
		        				$hasAccess = false;
		        				break;
		        			}
		        		}
		        	}

		    	}
		    	// Bis hier...
		    	// <----

				if(!$hasAccess) {

					$aro = "$module.$controller.$action";
					$url = WSB_ADMIN_URL . "$module/$controller/$action";
					WSB_Log::err('Missing permission for '. $aro);

					$request->setModuleName('default');
					$request->setControllerName('error');
					$request->setActionName('accessdenied');

				}


			} else {

				$request->setModuleName('default' );
				$request->setControllerName('auth');
				$request->setActionName('login');

			}

		// Login
		} else {

			$request->setModuleName('default');
			$request->setControllerName('auth');
			$request->setActionName('login');

		}

    }

}